<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('仓库编号')">
              <a-input :placeholder="$t('请输入仓库编号')" v-model="queryParam.code"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('仓库名称')">
              <a-input :placeholder="$t('请输入仓库名称')" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="4" :lg="6" :md="8" :sm="24">
              <a-form-item :label="$t('管理状态')">
                <j-switch :placeholder="$t('请选择管理状态')" v-model="queryParam.state" query></j-switch>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantid">
              <a-form-item :label="$t('门店')">
                <a-select v-model="queryParam.tenantId">
                  <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                    >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-has="'BisGoodsStoreController:add'">{{ $t('新增') }}</a-button>
      <a-button type="primary" icon="download" :loading="exloading" @click="handleExportXls($t('仓库设置'))" v-has="'BisGoodsStoreController:export'">{{
        $t('导出')
      }}</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :expandedRowKeys="expandedRowKeys"
        @change="handleTableChange"
        @expand="handleExpand"
      >
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span
          slot="action"
          slot-scope="text, record"
          v-if="(!record.tenantId && !tenantid) || record.tenantId == tenantid"
        >
          <a @click="handleAddChild(record)" v-has="'BisGoodsStoreController:add'">{{ $t('添加下级') }}</a>
          <a-divider type="vertical" v-has="'BisGoodsStoreController:add'"/>
          <a @click="handleEdit(record)" v-has="'BisGoodsStoreController:edit'">{{ $t('编辑') }}</a>
          <a-divider type="vertical"  v-has="'BisGoodsStoreController:edit'"/>
          <a-popconfirm :title="$t('确定删除吗?')" @confirm="() => handleDeleteNode(record.id)" placement="topLeft">
            <a v-has="'BisGoodsStoreController:delete'">{{ $t('删除') }}</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>

    <bisGoodsStore-modal ref="modalForm" @ok="modalFormOk"></bisGoodsStore-modal>
  </a-card>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import { getAction, deleteAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import { filterObj } from '@/utils/util'
import BisGoodsStoreModal from './modules/BisGoodsStoreModal'

export default {
  name: 'GoodsStoreList',
  mixins: [JeecgListMixin],
  components: {
    BisGoodsStoreModal,
  },
  data() {
    return {
      description: '仓库管理管理页面',
      // 表头
      columns: [
        {
          title: this.$t('仓库名称'),
          align: 'left',
          dataIndex: 'name',
        },
        {
          title: this.$t('仓库编号'),
          align: 'left',
          dataIndex: 'code',
        },
        {
          title: this.$t('管理状态'),
          align: 'left',
          dataIndex: 'state',
          customRender: (text) => (!text ? '' : text == 'Y' ? this.$t('是') : this.$t('否')),
        },
        {
          title: this.$t('仓库位置'),
          align: 'left',
          dataIndex: 'sddress',
        },
        {
          title: this.$t('备注'),
          align: 'left',
          dataIndex: 'comment',
        },
        {
          title: this.$t('操作'),
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/goods/bisGoodsStore/rootList',
        childList: '/goods/bisGoodsStore/childList',
        getChildListBatch: '/goods/bisGoodsStore/getChildListBatch',
        delete: '/goods/bisGoodsStore/delete',
        deleteBatch: '/goods/bisGoodsStore/deleteBatch',
        exportXlsUrl: '/goods/bisGoodsStore/exportXls',
        importExcelUrl: 'goods/bisGoodsStore/importExcel',
      },
      expandedRowKeys: [],
      hasChildrenField: 'hasChild',
      pidField: 'pid',
      dictOptions: {},
      loadParent: false,
      superFieldList: [],
      tenantid: Vue.ls.get(TENANT_ID),
      shops: [],
      queryParam: {
        tenantId: '',
      },
    }
  },
  created() {
    if (!this.tenantid) {
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: 0, title: this.$t('总部') })
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
      this.columns.splice(2, 0, {
        title: this.$t('所属门店'),
        align: 'left',
        dataIndex: 'tenantId',
        customRender: (t, r) => {
          let str
          if (!t) {
            str = this.$t('总部')
          } else {
            str = r.tenantId_dictText ? t + ' ' + r.tenantId_dictText : t
          }
          return str
        },
      })
    }
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => (_this.selectedRowKeys = selectedRowKeys),
        },
      }
    },
  },
  methods: {
    loadData(arg) {
      if (arg == 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams()
      params.hasQuery = 'true'
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            let result = res.result
            if (Number(result.total) > 0) {
              this.ipagination.total = Number(result.total)
              this.dataSource = this.getDataByResult(res.result.records)
              return this.loadDataByExpandedRows(this.dataSource)
            } else {
              this.ipagination.total = 0
              this.dataSource = []
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
    loadDataByExpandedRows(dataList) {
      if (this.expandedRowKeys.length > 0) {
        return getAction(this.url.getChildListBatch, { parentIds: this.expandedRowKeys.join(',') }).then((res) => {
          if (res.success && res.result.records.length > 0) {
            //已展开的数据批量子节点
            let records = res.result.records
            const listMap = new Map()
            for (let item of records) {
              let pid = item[this.pidField]
              if (this.expandedRowKeys.join(',').includes(pid)) {
                let mapList = listMap.get(pid)
                if (mapList == null) {
                  mapList = []
                }
                mapList.push(item)
                listMap.set(pid, mapList)
              }
            }
            let childrenMap = listMap
            let fn = (list) => {
              if (list) {
                list.forEach((data) => {
                  if (this.expandedRowKeys.includes(data.id)) {
                    data.children = this.getDataByResult(childrenMap.get(data.id))
                    fn(data.children)
                  }
                })
              }
            }
            fn(dataList)
          }
        })
      } else {
        return Promise.resolve()
      }
    },
    getQueryParams(arg) {
      //获取查询条件
      let sqp = {}
      let param = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      if (arg) {
        param = Object.assign(sqp, this.isorter, this.filters)
      } else {
        param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      }
      if (JSON.stringify(this.queryParam) === '{}' || arg) {
        param.hasQuery = 'false'
      } else {
        param.hasQuery = 'true'
      }
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    searchReset() {
      //重置
      this.expandedRowKeys = []
      this.queryParam = {
        tenantId: '',
      }
      this.loadData(1)
    },
    getDataByResult(result) {
      if (result) {
        return result.map((item) => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    handleExpand(expanded, record) {
      // 判断是否是展开状态
      if (expanded) {
        this.expandedRowKeys.push(record.id)
        if (record.children.length > 0 && record.children[0].isLoading === true) {
          let params = this.getQueryParams(1) //查询条件
          params[this.pidField] = record.id
          params.hasQuery = 'false'
          params.superQueryParams = ''
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.result.records) {
                record.children = this.getDataByResult(res.result.records)
                this.dataSource = [...this.dataSource]
              } else {
                record.children = ''
                record.hasChildrenField = '0'
              }
            } else {
              this.$message.warning(res.message)
            }
          })
        }
      } else {
        let keyIndex = this.expandedRowKeys.indexOf(record.id)
        if (keyIndex >= 0) {
          this.expandedRowKeys.splice(keyIndex, 1)
        }
      }
    },
    handleAddChild(record) {
      this.loadParent = true
      let obj = {}
      obj[this.pidField] = record['id']
      this.$refs.modalForm.add(obj)
    },
    handleDeleteNode(id) {
      if (!this.url.delete) {
        this.$message.error(this.$t('请设置url.delete属性'))
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.loadData(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    batchDel() {
      let that = this
      if (that.selectedRowKeys.length <= 0) {
        that.$message.warning(that.$t('请选择一条记录！'))
        return false
      } else {
        let ids = ''
        that.selectedRowKeys.forEach(function (val) {
          ids += val + ','
        })
        that.$confirm({
          title: that.$t('确认删除'),
          content: that.$t('是否删除选中数据?'),
          okText: that.$t("确定"),
          cancelText: that.$t("取消"),
          onOk: function () {
            that.handleDeleteNode(ids)
            that.onClearSelected()
          },
        })
      }
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({
        type: 'string',
        value: 'pid',
        text: '父级节点',
        dictCode: "bis_goods_kind where pid = '0',name,id",
      })
      fieldList.push({ type: 'string', value: 'code', text: '仓库编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'name', text: '仓库名称', dictCode: '' })
      fieldList.push({ type: 'switch', value: 'state', text: '管理状态' })
      fieldList.push({ type: 'string', value: 'sddress', text: '仓库位置', dictCode: '' })
      fieldList.push({ type: 'string', value: 'comment', text: '备注', dictCode: '' })
      this.superFieldList = fieldList
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>